15. Quiz: Warp the Perspective

Transform a license plate

Now, it's your turn to create a geometric transform! Geometric transforms are often useful for aligning text for better readability; from scanning important documents to reading in information about a scene in the world.

In this example, you'll be using a geometric transform to warp the appearance of a license plate on a car so that it appears as if it's being viewed from the front. As below, aim to make the license plate a perfect rectangle in the x-y plane.

Car with a geometric transform applied

Car with a geometric transform applied

Note on Code Quizzes

Some code will have been implemented for you, typically at the top of a quiz and again at the bottom for display. The code you need to implement will be marked as TODO tasks. Remember to test your code to visualize the output before you submit!

Start Quiz:

import numpy as np
import matplotlib.pyplot as plt
import cv2

# Read in the image
image = cv2.imread('license_plate_skew.jpg')
# Convert to RGB (from BGR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# ---------------------------------------------------------- #

## TODO: Define the geometric tranform function
## This function take in an image and returns a 
## geometrically transformed image
def geo_tx(image):
    image_size = (image.shape[1], image.shape[0])
    
    ## TODO: Define the four source coordinates
    source_pts = np.float32(
        [[0, 0],
         [0, 0],
         [0, 0],
         [0, 0]])
    
    ## TODO: Define the four destination coordinates    
    ## Tip: These points should define a 400x200px rectangle
    warped_pts = np.float32(
        [[0, 0],
         [0, 0],
         [0, 0],
         [0, 0]])
    
    ## TODO: Compute the perspective transform, M
    M = None
    
    ## TODO: Using M, create a warped image named `warped`
    warped = None

    return warped
    
    
# ---------------------------------------------------------- #
# Make a copy of the original image and warp it
warped_image = np.copy(image)
warped_image = geo_tx(warped_image)

if(warped_image is not None):
    # Visualize
    f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))
    ax1.set_title('Source image')
    ax1.imshow(image)
    ax2.set_title('Warped image')
    ax2.imshow(warped_image)
else:
    print('No warped image was returned by your function.')